package cn.psvmc.cxzapi.service.customer;

import cn.psvmc.cxzapi.config.ConfigKey;
import cn.psvmc.cxzapi.response.Result;
import cn.psvmc.cxzapi.response.ResultGenerator;
import cn.psvmc.cxzapi.service.system.ServiceUtil;
import cn.psvmc.cxzapi.util.OssService;
import cn.psvmc.cxzapi.util.ToolUtils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.net.URL;
import java.util.Date;
import java.util.Map;

/**
 * @Author YWX
 * @Classname FileUploadService
 * @Description 文件上传
 * @Date 2024/9/8 18:02
 **/
@Service
@Slf4j
public class FileUploadService {
    @Resource
    private ServiceUtil serviceUtil;

    /**
     * @Description 使用临时授权上传文件到oss
     * @Date 2024/9/8 21:27
     * @Author YWX
     * @Param [file, map]
     * @Return cn.psvmc.cxzapi.response.Result
     **/
    public Result uploadOss2(MultipartFile file, Map<String, String> map) {
        //map.putAll(map2);
        // OSS访问域名。以华东1（杭州）地域为例，填写为https://oss-cn-hangzhou.aliyuncs.com。其它Region请按实际情况填写。
        String endpoint = ConfigKey.endpoint2;
        String bucketName2 = ConfigKey.bucketName2;
        Map<String, String> map2 = serviceUtil.getSts();
        String objectKey = map.get("filepath");
        // 从环境变量中获取步骤5生成的临时访问密钥AccessKey ID和AccessKey Secret，非阿里云账号AccessKey ID和AccessKey Secret。
        String accessKeyId = map2.get("accessKeyId");
        String accessKeySecret = map2.get("accessKeySecret");
        // 从环境变量中获取步骤5生成的安全令牌SecurityToken。
        String securityToken = map2.get("securityToken");

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build("https://" + endpoint, accessKeyId, accessKeySecret, securityToken);
        try {
            // 将本地文件exampletest.txt上传至examplebucket。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName2, objectKey, file.getInputStream());

            ObjectMetadata metadata = new ObjectMetadata();
            // 上传文件时设置存储类型。
            metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // 上传文件时设置读写权限ACL。
            metadata.setObjectAcl(CannedAccessControlList.Private);
            putObjectRequest.setMetadata(metadata);
            // 设置存储空间为公共读
            //ossClient.setBucketAcl(bucketName2, CannedAccessControlList.PublicRead);
            // 设置对象为公共读
            //ossClient.setObjectAcl(bucketName2, objectKey, CannedAccessControlList.PublicRead);
            //ossClient.setObjectAcl(bucketName2, objectKey, CannedAccessControlList.PublicReadWrite);
            //ossClient.setObjectAcl(bucketName2, objectKey, CannedAccessControlList.Private);
            // 上传文件。
            ossClient.putObject(putObjectRequest);
        } catch (Exception e) {
            FileUploadService.log.error("上传文件至OSS出错: {}", e.getMessage());
            return ResultGenerator.genFailResult("上传文件至OSS出错: " + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        String filepath = "https://" + bucketName2 + "." + endpoint + "/" + objectKey;
        // 假设ossClient是一个已经初始化好的OSSClient实例
        Date expiration = new Date(new Date().getTime() + 3600 * 1000); // 1小时后过期
        FileUploadService.log.info("生成预签名URL：{}", filepath);
        URL url = ossClient.generatePresignedUrl(bucketName2, objectKey, expiration);
        return ResultGenerator.genSuccessResult("上传文件至OSS成功！", url);
    }

    /**
     * @Description 上传文件到oss
     * @Date 2024/9/8 21:27
     * @Author YWX
     * @Param [file, map]
     * @Return cn.psvmc.cxzapi.response.Result
     **/
    public Result uploadOss(MultipartFile file, Map<String, String> map) {
        String filepath = map.get("filepath");
        if (ToolUtils.isEmpty(filepath)) {
            filepath = OssService.uploadFile(file, "csz_mp");
        } else {
            filepath = OssService.uploadFile2(file, filepath);
        }
        return ResultGenerator.genSuccessResult("上传文件至OSS成功！", filepath);
    }
}
